package de.idgard.android.addon.ui;

import java.net.URLConnection;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.http.SslCertificate.DName;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JsPromptResult;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import de.idgard.android.R;
import de.idgard.android.addon.annotation.ContainerInteraction;
import de.idgard.android.addon.js.IDGardJSHandler;
import de.idgard.android.addon.services.GlobalServiceRegistry;
import de.idgard.android.addon.ui.anim.ToolbarCustomAnimationMgr;
import de.idgard.android.addon.ui.component.CustomWebProgressBar;
import de.idgard.android.addon.ui.dialogs.IDGPrivacyCounterDialog;
import de.idgard.android.addon.ui.dialogs.IDGardNewsDialog;
import de.idgard.android.addon.ui.dialogs.IDGardSaveBookmarkDialog;
import de.idgard.android.addon.ui.dialogs.IDGardUpdateDialog;
import de.idgard.android.addon.ui.dialogs.TransparencyDialog;
import de.idgard.android.addon.ui.services.AddonStateService;
import de.idgard.android.addon.ui.services.BrowserTabService;
import de.idgard.android.addon.ui.services.BrowserUtilityService;
import de.idgard.android.addon.ui.services.OrchestrationService;
import de.idgard.android.addon.ui.services.PreferenceService;
import de.idgard.android.addon.ui.services.PropertiesService;
import de.idgard.android.addon.ui.services.TransparencyStateService;
import de.idgard.android.addon.ui.services.ZircoToIDGardAPI;
import de.idgard.android.addon.ui.services.dto.MessageDTO;

/**
 * 
 * @author ckaratza
 * 
 * @author pratik popat
 * 
 */

public final class AddonUIManager {

	private ZircoToIDGardAPI getZircoToIDGardAPI() {
		return GlobalServiceRegistry.instance().getZircoToIDGardAPI();
	}

	private OrchestrationService getOrchestrationService() {
		return GlobalServiceRegistry.instance().getOrchestrationService();
	}

	private BrowserTabService getBrowserTabService() {
		return GlobalServiceRegistry.instance().getBrowserTabService();
	}

	private TransparencyStateService getTransparencyStateService() {
		return GlobalServiceRegistry.instance().getTransparencyStateService();
	}

	private AddonStateService getAddonStateService() {
		return GlobalServiceRegistry.instance().getAddonStateService();
	}

	private PreferenceService getPreferenceService() {
		return GlobalServiceRegistry.instance().getPreferenceService();
	}

	private PropertiesService getPropertiesService() {
		return GlobalServiceRegistry.instance().getPropertiesService();
	}

	private BrowserUtilityService getBrowserUtilityService() {
		return GlobalServiceRegistry.instance().getBrowserUtilityService();
	}

	private static AddonUIManager instance = new AddonUIManager();

	@ContainerInteraction
	public void openIDGardAddBookmarksDialog() {
		new IDGardSaveBookmarkDialog(containerActivity, getZircoToIDGardAPI().getContainersCurrentView()).show();
		toolbarManager.setToolbarVisibility(false);
	}

	@ContainerInteraction
	public boolean isOnline(Context c) {
		ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();

		if (ni != null && ni.isConnected())
			return true;
		else
			return false;
	}

	@ContainerInteraction
	public boolean isChangelogStartupPopupSuppressed() {
		return Boolean.valueOf(getPropertiesService().getString(R.string.suppressChangeLog));
	}

	@ContainerInteraction
	public boolean useIDGardTabMode() {
		return Boolean.valueOf(getPropertiesService().getString(R.string.useIdgardTabMode));
	}

	@ContainerInteraction
	public void addIDGardHeadersToUrlConnection(URLConnection conn) {
		if (getAddonStateService().isAddonON()) {
			StringBuilder sb = new StringBuilder();
			sb.append(getPropertiesService().getString(R.string.idgardidcookie)).append("=")
					.append(GlobalServiceRegistry.instance().getBrowserUtilityService().getIDGardData().getIdgardId()).append(";")
					.append(getPropertiesService().getString(R.string.jsessionidcookie)).append("=")
					.append(GlobalServiceRegistry.instance().getBrowserUtilityService().getIDGardData().getJsessionId()).append(";")
					.append(getPropertiesService().getString(R.string.crosssitepreventioncookie)).append("=")
					.append(GlobalServiceRegistry.instance().getBrowserUtilityService().getIDGardData().getCrossSitePrevention()).append(";");
			conn.setRequestProperty("set-cookie", sb.toString());
			conn.setRequestProperty("cookie", sb.toString());
		}
	}

	@ContainerInteraction
	public boolean checkIfCerificateIssuerIsUniscon(DName dname) {
		return getBrowserUtilityService().checkIfCertificateIssuerIsUniscon(dname);
	}

	@ContainerInteraction
	public void restoreAddonState() {
		MessageDTO dto = getOrchestrationService().restoreAddonState();
		if (dto.hasAction("updateIDGardGui")) {
			updateIDGardGui();
		}
	}

	@ContainerInteraction
	public CharSequence customizeHistoryQuery(CharSequence constraint) {
		if (getAddonStateService().isAddonON()) {
			return getPropertiesService().getString(R.string.aboutstart);
		}
		return constraint;
	}

	@ContainerInteraction
	public boolean checkIfIDGardJSPrompt(String message) {
		return message.startsWith(getPropertiesService().getString(R.string.idgardjspromptindicator));
	}

	@ContainerInteraction
	public void setFullScreenMode() {
		containerActivity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}

	@ContainerInteraction
	public void handleIDGardJSPrompt(String message, String defaultValue, final JsPromptResult result) {
		IDGardJSHandler.getInstance().handleIDGardJs(message, defaultValue, result);
	}

	@ContainerInteraction
	public void handleApplicationExit() {
		getOrchestrationService().handleApplicationExit();
	}

	@ContainerInteraction
	public void initializeAddon(Activity activity) {
		this.containerActivity = activity;
		GlobalServiceRegistry.instance().init(containerActivity);
		IDGardJSHandler.getInstance().setContext(activity);
		initialize();
	}

	@ContainerInteraction
	public void resume() {
		if (getAddonStateService().isAddonONLOGIN() && !performingLogin) {
			openLoginPage();
		} else {
			performingLogin = false;
		}
	}

	@ContainerInteraction
	private Activity containerActivity;

	@ContainerInteraction
	private Object findViewById(int id) {
		return containerActivity.findViewById(id);
	}

	public void checkUrlAndUpdateStateAndUI(final String url) {
		if (getOrchestrationService().checkUrlAndReact(url)) {
			this.updateIDGardGui();
		}
	}

	public void updateIDGardGui() {
		updateIdGardOnOffView();
	}

	public void configureWebView(WebView view) {
		getOrchestrationService().configureWebView(view);
	}

	public void checkLoadedUrlForCookiesAndAdjustStateAndSettings(final String url) {
		MessageDTO dto = getOrchestrationService().handleLoadedUrl(url, getZircoToIDGardAPI().getContainersCurrentView());
		if (dto.hasAction("openLoginPage") && !performingLogin) {
			openLoginPage();
		}
		if (dto.hasAction("updateIDGardGui")) {
			updateIDGardGui();
		}
		if (dto.hasAction("loginCompleted")) {
			if (handler != null) {
				handler.sendEmptyMessage(0);
				handler = null;
			}
			getOrchestrationService().handleExistingViewsUponLogin();
			performingLogin = false;
		}
	}

	private ImageView idgardOnButton;
	private Button idgardTransButton;
	private ImageView idgardMoreOptionButton;
	private ImageView idgardNewsButtonOnLogin;
	private Button idgardHelpBtn, idgardBookmarkBtn, idgardHomeBtn, idgardCreditBtn, idgardMailsBtn, idgardFeedbackBtn, idgardCounterBtn, idgardNewsButtonOn;

	private LinearLayout idgardBackgroundLayoutOnMode;

	private RelativeLayout idgardBackgroundLayoutOnModeLogin;
	private LinearLayout idgardMoretoolbarlayout;

	private ImageView idgardMainImageOnMode, idgardMainImageOnModeLogin;
	private ImageView mainlogo, vd1, vd2, vd3;

	private TextView tvAddonVersionText;

	private TransparencyDialog transparencydialog;

	private LinearLayout moretoolsTouchpad;

	private ToolbarCustomAnimationMgr toolbarManager;

	/* progress bar variables */
	private CustomWebProgressBar cusProgressBar;
	public int mProgress = 0;

	private void initialize() {
		mainlogo = (ImageView) findViewById(R.id.IDGardMainIconOnMode);
		vd1 = (ImageView) findViewById(R.id.IDGardVerticalDivider21);
		vd2 = (ImageView) findViewById(R.id.IDGardVerticalDivider221);
		vd3 = (ImageView) findViewById(R.id.IDGardVerticalDivider23);
		idgardHelpBtn = (Button) findViewById(R.id.IDGardHelpBtn);
		idgardBookmarkBtn = (Button) findViewById(R.id.IDGardBookmarkBtn);
		idgardHomeBtn = (Button) findViewById(R.id.IDGardHomeBtn);
		idgardCreditBtn = (Button) findViewById(R.id.IDGardCreditBtn);
		idgardMailsBtn = (Button) findViewById(R.id.IDGardMailsBtn);
		idgardFeedbackBtn = (Button) findViewById(R.id.IDGardFeedbackBtn);
		idgardCounterBtn = (Button) findViewById(R.id.IDGardCounterBtn);
		idgardTransButton = (Button) findViewById(R.id.IDGardTransBtn);
		idgardNewsButtonOn = (Button) findViewById(R.id.IDGardNewsbtnGreen);

		tvAddonVersionText = (TextView) findViewById(R.id.IDGardVersionText);

		/* idgard layouts */
		idgardMoretoolbarlayout = (LinearLayout) findViewById(R.id.IdGardMoreToolsLayout);
		idgardBackgroundLayoutOnModeLogin = (RelativeLayout) findViewById(R.id.IDGardOnModeLogin);
		idgardBackgroundLayoutOnMode = (LinearLayout) findViewById(R.id.IdGardOnModeLayout);

		/* idgard views */
		idgardMainImageOnModeLogin = (ImageView) findViewById(R.id.IDGardMainIconOnModeLogin);
		idgardMainImageOnMode = (ImageView) findViewById(R.id.IDGardMainIconOnMode);

		idgardOnButton = (ImageView) findViewById(R.id.IDGuardOnbtn);
		idgardNewsButtonOnLogin = (ImageView) findViewById(R.id.IDGardNewsbtnOnLogin);
		idgardMoreOptionButton = (ImageView) findViewById(R.id.IDGardArrowUpbtnGreen);

		/*-ProgressBars--*/
		cusProgressBar = new CustomWebProgressBar(containerActivity, true);

		/* tool bar */
		moretoolsTouchpad = (LinearLayout) findViewById(R.id.IDGardMoreToolbarTouchPad);

		toolbarManager = new ToolbarCustomAnimationMgr(containerActivity, idgardMoretoolbarlayout, idgardBackgroundLayoutOnMode);
	}

	public void updateIDGardGUI() {

		if (getTransparencyStateService().isTransparent()) {
			idgardBackgroundLayoutOnMode.setBackgroundResource(R.drawable.idgard_bar_bk_yellow);
			idgardMoreOptionButton.setBackgroundResource(R.drawable.idgard_more_arrow_open);
			mainlogo.setImageResource(R.drawable.idgard_logo_off);
			vd1.setImageResource(R.drawable.idgard_vertical_divider_white);
			vd2.setImageResource(R.drawable.idgard_vertical_divider_white);
			vd3.setImageResource(R.drawable.idgard_vertical_divider_white);
		} else {
			idgardBackgroundLayoutOnMode.setBackgroundResource(R.drawable.idgard_bar_bk_green);
			idgardMoreOptionButton.setBackgroundResource(R.drawable.idgard_more_arrow);
			mainlogo.setImageResource(R.drawable.idgard_logo_on);
			vd1.setImageResource(R.drawable.idgard_vertical_divider_green);
			vd2.setImageResource(R.drawable.idgard_vertical_divider_green);
			vd3.setImageResource(R.drawable.idgard_vertical_divider_green);
		}
	}

	public void buildIDGardUI() {

		transparencydialog = new TransparencyDialog(containerActivity);

		/* Redirecting to idgard server if true */
		if (getAddonStateService().isAddonON()) {
			if (getZircoToIDGardAPI().isLoading()) {
				getZircoToIDGardAPI().stopLoading();
			}
			getZircoToIDGardAPI().navigateToUrl(getBrowserUtilityService().getIDGardServerUrl());
		}

		/* Show offMode Gui if false */
		else {
			updateIdGardOnOffView();
		}

		idgardMoretoolbarlayout.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// Dummy event prevent from showHideRunnable()
			}
		});

		moretoolsTouchpad.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (toolbarManager.getToolLayoutVisibility()) toolbarManager.handleToolbarpadTouch(event);
				return true;
			}
		});

		idgardMoreOptionButton.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (!toolbarManager.getToolLayoutVisibility()) {
					toolbarManager.handleToolbarTouch(event);
				}
				return true;
			}
		});

		idgardBackgroundLayoutOnMode.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (!toolbarManager.getToolLayoutVisibility()) {
					toolbarManager.handleToolbarTouch(event);
				}
				return true;
			}
		});

		/* idgard image events */

		idgardMainImageOnMode.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

			}
		});

		idgardMainImageOnModeLogin.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});
		/*----*/

		idgardOnButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				getOrchestrationService().handleAddonClosinFromExistingState();
				updateIdGardOnOffView();
				showToast(containerActivity.getResources().getString(R.string.toast_idgardoff), Toast.LENGTH_SHORT, Gravity.CENTER, 0, 0, 0, 0);
				if (toolbarManager.getToolLayoutVisibility()) {
					toolbarManager.setToolbarVisibility(false);
				}
				openLoginPage();
			}

		});

		/* IDGARD tool buttons listeners.. */

		idgardNewsButtonOn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showNewsDialog();
				toolbarManager.setToolbarVisibility(false);
			}
		});

		idgardNewsButtonOnLogin.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showNewsDialog();
			}
		});

		idgardHomeBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				getBrowserTabService().addNewTab();
				getZircoToIDGardAPI().navigateToUrl(getPropertiesService().getString(R.string.system_idgard_home_url));
				toolbarManager.setToolbarVisibility(false);
			}
		});

		idgardCreditBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				getBrowserTabService().addNewTab();
				getZircoToIDGardAPI().navigateToUrl(getPropertiesService().getString(R.string.system_idgard_credit_url));
				toolbarManager.setToolbarVisibility(false);
			}
		});

		idgardBookmarkBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				openIDGardAddBookmarksDialog();
			}

		});

		idgardMailsBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				getBrowserTabService().addNewTab();
				getZircoToIDGardAPI().navigateToUrl(getPropertiesService().getString(R.string.system_idgard_mails_url));
				toolbarManager.setToolbarVisibility(false);
			}
		});

		idgardFeedbackBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				getBrowserTabService().addNewTab();
				getZircoToIDGardAPI().navigateToUrl(getPropertiesService().getString(R.string.system_idgard_feedback_url));
				toolbarManager.setToolbarVisibility(false);
			}
		});

		idgardCounterBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				new IDGPrivacyCounterDialog(containerActivity).show();
				toolbarManager.setToolbarVisibility(false);
			}
		});

		idgardHelpBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				getBrowserTabService().addNewTab();
				getZircoToIDGardAPI().navigateToUrl(getPropertiesService().getString(R.string.system_idgard_help_url));
				toolbarManager.setToolbarVisibility(false);
			}
		});

		idgardTransButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				transparencydialog.show();
				toolbarManager.setToolbarVisibility(false);
			}
		});

		tvAddonVersionText.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				new IDGardUpdateDialog(containerActivity, null).show();
			}
		});

		/* load idgard preferences for hide show idgard bar... */
		loadPreferences();

	}

	public void updateIdGardOnOffView() {
		if (getPreferenceService().getSavedAddonVisibilityMode()) {
			idgardBackgroundLayoutOnMode.setVisibility(View.GONE);
			idgardBackgroundLayoutOnModeLogin.setVisibility(View.GONE);
			return;
		}

		if (getAddonStateService().isAddonON()) {
			if (getZircoToIDGardAPI().isLoading()) {
				getZircoToIDGardAPI().stopLoading();
			}
			idgardBackgroundLayoutOnMode.setVisibility(View.VISIBLE);
			idgardBackgroundLayoutOnModeLogin.setVisibility(View.GONE);
		} else if (getAddonStateService().isAddonONLOGIN()) {
			idgardBackgroundLayoutOnMode.setVisibility(View.GONE);
			idgardBackgroundLayoutOnModeLogin.setVisibility(View.VISIBLE);

		}
	}

	public void showToast(String toastText, int duration, int gravity, int xoffset, int yoffset, float horizontalMargin, float verticalMargin) {
		Toast toast = Toast.makeText(containerActivity, toastText, duration);
		toast.setGravity(gravity, xoffset, yoffset);
		toast.setMargin(horizontalMargin, verticalMargin);
		toast.show();
	}

	public void progressChange() {
		Log.i(this.getClass().getName(), "Progress:" + mProgress);
		mProgress = getZircoToIDGardAPI().getContainersCurrentView().getProgress();
		cusProgressBar.setProgress(mProgress);
		if (handler != null) {
			Message msg = new Message();
			Bundle b = new Bundle();
			b.putInt("progress", mProgress);
			msg.setData(b);
			handler.sendMessage(msg);
		}
	}

	public static AddonUIManager getInstance() {
		return instance;
	}

	public void onTouch() {
		if (toolbarManager.getToolLayoutVisibility()) {
			toolbarManager.setToolbarVisibility(false);
		}
	}

	private void showNewsDialog() {
		new IDGardNewsDialog(containerActivity).show();
	}

	public CheckBoxPreference getAddonHideIDGardPreference() {

		CheckBoxPreference hideAddonPref = new CheckBoxPreference(containerActivity);
		hideAddonPref.setTitle(R.string.hidIdGardBar);
		hideAddonPref.setKey("GeneralHideIDGardBar");
		hideAddonPref.setSummary(R.string.hidIdGardBarSummary);
		hideAddonPref.setDefaultValue(false);

		return hideAddonPref;
	}

	/* load idgard preferences like hide idgrad bar etc... */
	public void loadPreferences() {
		SharedPreferences hideBarPref = PreferenceManager.getDefaultSharedPreferences(containerActivity);
		boolean hide = hideBarPref.getBoolean("GeneralHideIDGardBar", false);
		if (hide) {
			idgardBackgroundLayoutOnMode.setVisibility(View.GONE);
			idgardBackgroundLayoutOnModeLogin.setVisibility(View.GONE);
		}
	}

	private void openLoginPage() {
		boolean openWithWebApp = getBrowserUtilityService().checkIfOpenLoginPageWithWebApp();
		if (openWithWebApp) {
			getZircoToIDGardAPI().navigateToUrl(getBrowserUtilityService().getIDGardServerUrl());
		} else {
			if (!performingLogin) {

				Intent intent = new Intent(containerActivity, LoginActivity.class);
				containerActivity.startActivity(intent);
			}
		}
	}

	public Activity getContainerActivity() {
		return containerActivity;
	}

	private boolean performingLogin;

	private Handler handler = null;

	/**
	 * 
	 */
	public void performLogin(Handler handler) {
		this.performingLogin = true;
		getZircoToIDGardAPI().navigateToUrl(getPropertiesService().getString(R.string.idgard_home_url));
		this.handler = handler;
	}

	public ToolbarCustomAnimationMgr getToolbarManager() {
		return toolbarManager;
	}

}
